/**
 * $Id$
 * @author mcanovas
 * @date   Mar 7, 2012 9:13:52 AM
 *
 * Copyright (C) 2012 Scytl Secure Electronic Voting SA
 *
 * All rights reserved.
 *
 */
package org.sk.gsync.app.mybatis;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface QueueMapper {

    @Update("CREATE TABLE IF NOT EXISTS QUEUE ( " + "ID INTEGER, "
        + "PATH VARCHAR2(255) PRIMARY KEY, "
        + "RESOURCE_ID VARCHAR2(40), "
        + "ELEMENT_TYPE VARCHAR2(40) NOT NULL, "
        + "LAST_MODIFIED NUMBER(20))")
    void createTable();

    @Insert("INSERT INTO QUEUE ()" + "VALUES (#{item.id}, "
        + "#{item.resourceID}, #{item.elementType}, #{item.lastModified})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(@Param("item") QueueItem item);

    @Update("UPDATE TABLE QUEUE "
        + "SET ELEMENT_TYPE = #{item.elementType} "
        + "SET LAST_MODIFIED = #{item.lastModified} "
        + "SET RESOURCE_ID = #{item.resourceID} "
        + "WHERE ID = #{item.id}")
    void update(@Param("item") QueueItem item);

    @Delete("DELETE FROM QUEUE WHERE ID = #{item.id}")
    void delete(@Param("item") QueueItem item);

    @Select("SELECT Q.ID AS ID, " + "Q.PATH AS PATH "
        + "Q.RESOURCE_ID AS RESOURCE_ID, "
        + "Q.ELEMENT_TYPE AS ELEMENT_TYPE, "
        + "Q.LAST_MODIFIED AS LAST_MODIFIED " + "FROM QUEUE Q "
        + "WHERE Q.ID = #{id}")
    List<QueueItem> findByPrimaryKey(@Param("id") String id);

    @Select("SELECT Q.ID AS ID, " + "Q.PATH AS PATH "
        + "Q.RESOURCE_ID AS RESOURCE_ID, "
        + "Q.ELEMENT_TYPE AS ELEMENT_TYPE, "
        + "Q.LAST_MODIFIED AS LAST_MODIFIED " + "FROM QUEUE Q "
        + "ORDER BY Q.ID ASC " + "LIMIT 1")
    QueueItem findFirst();

}
